import os
from sys import exc_info

class Config:
    def __init__(self,inputFile="configUser.txt",guid="1234567890"):
        self.genericProperties = setDefaultGenerics()
        self.configFile = inputFile
        d = os.path.dirname("InputArchive/")
        if not os.path.exists(d):
            os.makedirs(d)
        try:
            with open(str(os.getcwd())+"\\ConfigFiles\\"+inputFile, 'r') as myFile:
                archive = open("InputArchive/"+str(guid)+".txt",'w')
                for line in myFile:
                    archive.write(line)
                    line = line.strip()
                    if not line:
                        continue
                    if line[0]=="#":
                        continue
                    (key, sep, values) = line.partition(":")
                    key=key.lower()
                    if "," in values:
                        self.genericProperties[key] = getObject(line)
                    else:
                        self.genericProperties[key] = values.strip()
                archive.close()
        #except IOError as e:
        #    print "It appears that the inputFile ConfigFiles/%s doesn't exist."%(inputFile)
        except:
            print "The Config File failed for an unknown reason: ", exc_info()[1]
            raise
    def getProperty(self, key):
        try:
            val = self.genericProperties[key.lower()]
            return val
        except:
            return ""
    def hasProperty(self, key):
        return key.lower() in self.genericProperties
            

def getObject(line):
    strValues = line.split(":")[1].strip()
    values = [x.strip() for x in strValues.split(",")]
    ret = None
    if "=" in strValues:
        ret = {}
        for val in values:
            (key, value) = val.split("=")
            key = key.strip()
            value = value.strip()
            if ";" in value:
                value = [x.strip() for x in value.split(";")]
            if "->" in key:
                (key1, key2) = key.split("->")
                ret[key1, key2] = value
            else:
                ret[key] = value
    else:
        ret = []
        for val in values:
            ret.append(val)
    return ret

def setDefaultGenerics():
    props = {}
    props['username']='lwooley@completesolar.com'
    props['password']='solar123solar'
    props['cutility1']='291'
    props['cheight1']='500'
    props['clength1']='500'
    props['soiling']='2'
    props['usetou']='1'
    props['inoct1']='44'
    props['invid_a1']='917'
    props['inverterid']='917'
    props['presolarrate1']='4042'
    props['collectorid']='2352'
    props['crate1']='4060'
    props['tilt1']='20'
    props['siteassessment']='0'
    return props
